package com.hnxxxy.common.shiro;

import com.hnxxxy.common.jwt.JwtToken;
import com.hnxxxy.sysmgr.pojo.Staff;
import com.hnxxxy.sysmgr.service.SysService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * JwtRealm 只负责校验 JwtToken
 */
@Slf4j
public class JwtRealm extends AuthorizingRealm {

	@Autowired
	private SysService userSerivce;
	/**
	 * 限定这个 Realm 只处理我们自定义的 JwtToken
	 */
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof JwtToken;
	}

	/**
	 * 此处的 SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		JwtToken jwtToken = (JwtToken) authcToken;
		if (jwtToken.getPrincipal() == null) {
			throw new AccountException("JWT token参数异常！");
		}
		// 从 JwtToken 中获取当前用户
		String username = jwtToken.getPrincipal().toString();
		Staff user = userSerivce.findByName(username);
		// 用户不存在
		if (user == null) {
			throw new UnknownAccountException("用户不存在！");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, username, getName());
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		log.info("-->接口Token执行角色和权限授权");
		//给资源进行授权
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Staff user = (Staff) SecurityUtils.getSubject().getPrincipal();
		Set<String> rolesSet= userSerivce.findRolesByStaffId(user.getId());
		Set<String> premsSet= userSerivce.findPremsByStaffId(user.getId());
		info.addRoles(rolesSet);
		info.addStringPermissions(premsSet);
		return info;
	}

}
